<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'vouchers';
	public function __construct()
	{
		parent::__construct();
		// Load all the required classes
		$this->load->library('form_validation');
		
		$this->load->model('uploking_withdrawals_m');
		$this->load->model('uploking_users_m');
		$this->lang->load('uploking_admin');
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'money',
				'label' => 'lang:uploking_withdrawal_money_label',
				'rules' => 'trim|numeric|required|callback__check_code'
			),
			array(
				'field' => 'email_paypal',
				'label' => 'lang:uploking_withdrawal_paypal_email_label',
				'rules' => 'trim|max_length[255]|required|valid_email'
			),
			array(
				'field' => 'status',
				'label' => 'lang:uploking_withdrawal_status_label'
			)
		);
		
		$this->data->statusList = array(
			''		=> lang('uploking_withdrawal_status_all_label'),
			'0'		=> lang('uploking_withdrawal_status_pendding_label'),
			'1'		=> lang('uploking_withdrawal_status_processed_label')
		);
				
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
						->append_metadata(js('stoepje.voucher.js', 'voucher'))
						->append_metadata(css('stoepje.voucher.css', 'voucher'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		//set the base/default where clause
		$base_where = array();

		//add post values to base_where if f_module is posted
		$base_where = $this->input->post('f_status') != '' ? $base_where + array('f_status' => $this->input->post('f_status')) : $base_where;
		$base_where = $this->input->post('f_keywords') ? $base_where + array('keywords' => $this->input->post('f_keywords')) : $base_where;

		// Create pagination links
		$total_rows = $this->uploking_withdrawals_m->count_by($base_where);
		$pagination = create_pagination('admin/withdrawals/index', $total_rows);

		// Using this data, get the relevant results
		$withdrawals = $this->uploking_withdrawals_m->limit($pagination['limit'])->get_many_by($base_where);

		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$this->template
			->title($this->module_details['name'])
			->append_metadata(js('admin/filter.js'))
			->set('pagination', $pagination)
			->set('withdrawals', $withdrawals);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/withdrawals', $this->data) : $this->template->build('admin/index', $this->data);
			
	}
	
	public function create()
	{
		$this->form_validation->set_rules($this->validation_rules);
		if ($this->form_validation->run())
		{
			$id = $this->stoepje_vouchers_m->insert(array(
				'code'			=> $this->input->post('code'),
				'prize_id'		=> $this->input->post('prize_id'),
				'description'	=> $this->input->post('description'),
				'status'		=> $this->input->post('status'),
				'created_time'	=> time()
			));
			if ($id)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('stoepje_voucher_create_success_label'), $this->input->post('code')));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('stoepje_voucher_create_error_label'));
			}
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/voucher') : redirect('admin/voucher/edit/' . $id);
		}
		else
		{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$voucher->$field['field'] = set_value($field['field']);
			}
		}

		$this->template
			->title($this->module_details['name'], lang('stoepje_voucher_create_title'))
			->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
			->append_metadata(css('jquery/jquery.tagsinput.css'))
			->set('voucher', $voucher)
			->build('admin/form');
	}
	public function edit($id = 0)
	{
		$id OR redirect('admin/withdrawals');
		$withdrawal = $this->uploking_withdrawals_m->get($id);
		$user = $this->uploking_users_m->get($withdrawal->user_id);
		$withdrawal OR redirect('admin/withdrawals');
		$this->form_validation->set_rules($this->validation_rules);
	
		if ($this->form_validation->run())
		{
	
			$result = $this->uploking_withdrawals_m->update($id, array(
				'money'			=> $this->input->post('money'),
				'email_paypal'		=> $this->input->post('email_paypal'),
				'status'		=> $this->input->post('status')
			));
				
			if ($result){
				$this->session->set_flashdata(array('success' => lang('uploking_withdrawal_edit_success_label')));
			}else{
				$this->session->set_flashdata('error', $this->lang->line('uploking_withdrawal_edit_error_label'));
			}
	
			// Redirect back to the form or main page
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/withdrawals') : redirect('admin/withdrawals/edit/' . $id);
		}
	
		// Go through all the known fields and get the post values
		foreach ($this->validation_rules as $key => $field)
		{
			if (isset($_POST[$field['field']]))
			{
				$withdrawal->$field['field'] = set_value($field['field']);
			}
		}
		$this->template
		->title($this->module_details['name'], lang('uploking_withdrawal_edit_label'))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->set('user', $user)
		->set('withdrawal', $withdrawal)
		->build('admin/form');
	}
	public function delete($id = 0)
	{
		// Delete one
		$ids = ($id) ? array($id) : $this->input->post('action_to');
	
		// Go through the array of slugs to delete
		if ( ! empty($ids))
		{
			$voucher_names = array();
			foreach ($ids as $id)
			{
				// Get the current page so we can grab the id too
				if ($voucher = $this->stoepje_vouchers_m->get($id))
				{
					$this->stoepje_vouchers_m->delete($id);
					$voucher_names[] = $voucher->code;
				}
			}
		}
	
		// Some pages have been deleted
		if ( ! empty($voucher_names))
		{
			// Only deleting one page
			if (count($voucher_names) == 1)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('stoepje_voucher_delete_success_label'), $voucher_names[0]));
			}
			// Deleting multiple pages
			else
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('stoepje_voucher_delete_mass_success_label'), implode('", "', $voucher_names)));
			}
		}
		// For some reason, none of them were deleted
		else
		{
			$this->session->set_flashdata('notice', lang('stoepje_voucher_delete_error_label'));
		}
	
		redirect('admin/voucher');
	}
	public function action()
	{
		switch ($this->input->post('btnAction'))
		{			
			case 'delete':
				$this->delete();
				break;
			default:
				redirect('admin/voucher');
			break;
		}
	}
	public function _check_code($code = '', $id = 0){
		return true;
		$this->form_validation->set_message('_check_code', sprintf(lang('stoepje_voucher_code_already_existed_title'), $code));
		if($id){
			$this->uploking_withdrawals_m->where('id !=', $id);
		}
		if($this->uploking_withdrawals_m->get_by('code',$code)){
			return false;
		}else{
			return true;
		}
	}
	public function generate_code(){
		$length = 8;
		$validCharacters = "ABCDEFGHIJKLMNOPQRSTUXYVWZ1234567890";
		$validCharNumber = strlen($validCharacters);
		$result = "";
		for ($i = 0; $i < $length; $i++) {
			$index = mt_rand(0, $validCharNumber - 1);
			$result .= $validCharacters[$index];
		}
		if($this->_check_code($result)){
			$data = array('code' => $result);
			echo json_encode($data);
			return;
		}else{
			$this->generate_code();
		}
	}
}
